#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
文件说明：CRC.py
这个文件不对外开放，仅在模块内使用。主要是CRC计算的实现。
可以使用查表法对CRC计算速度进行优化。
------------------------------------------
时间            作者        版本号      记录
2021-7-6        李树益      1.0        完成CRC8和CRC16计算功能
"""
import struct
#===================================================================
#CRC计算的代码参考网上别人写过的C代码
#===================================================================
"""
C代码
x8+x2+x+1
unsigned char CRC8(unsigned char *data, unsigned int datalen)
{
	unsigned char wCRCin = 0x00;
	unsigned char wCPoly = 0x07;
	
	while (datalen--) 	
	{
		wCRCin ^= *(data++);
		for(int i = 0;i < 8;i++)
		{
			if(wCRCin & 0x80)
				wCRCin = (wCRCin << 1) ^ wCPoly;
			else
				wCRCin = wCRCin << 1;
		}
	}
	return (wCRCin);
}
"""
def CRC8(pdata,lenght):
	crc = 0
	i = 0
	while(lenght > i):
		crc ^= pdata[i]
		i += 1
		for _ in range(8):
			crc = crc & 0xff
			if( crc & 0x80 == 0x80):
				crc = (crc << 1)^ 0x07
			else:
				crc <<= 1
	crc = crc & 0xff
	crc = struct.pack('B',crc)
	return crc


"""
C代码
x16+x12+x5+1
unsigned short CRC16_XMODEM(unsigned char *data, unsigned int datalen)
{
	unsigned short wCRCin = 0x0000;
	unsigned short wCPoly = 0x1021;
	
	while (datalen--) 	
	{
		wCRCin ^= (*(data++) << 8);
		for(int i = 0;i < 8;i++)
		{
			if(wCRCin & 0x8000)
				wCRCin = (wCRCin << 1) ^ wCPoly;
			else
				wCRCin = wCRCin << 1;
		}
	}
	return (wCRCin);
}
"""
def CRC16(pdata,lenght):
	crc = 0
	i = 0
	while(lenght > i):
		crc ^= (pdata[i] << 8)
		i += 1
		for _ in range(8):
			crc = crc&0xffff
			if(crc & 0x8000 == 0x8000):
				crc = (crc << 1) ^ 0x1021
			else:
				crc = crc << 1
	crc = crc&0xffff
	crc = struct.pack('!H',crc)	#高位在前，低位在后
	return crc